<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        excel导入员工信息
        <upload-excel-component
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
        />
      </el-card>
    </div>
  </div>
</template>
<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  components: { UploadExcelComponent },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    /**
       * return [
       * {timeofEntry: 标准时间, username: "小王"}，
       * {timeofEntry: 标准时间, username: "小李"}
       * ]
       */
    transformData(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      console.log(results)
      return results.map(item => {
        // item: {入职时间：44900, 姓名: 小王}
        // Object.keys(item) ==> [入职时间, 姓名]
        const zhKeys = Object.keys(item)
        const obj = {}
        zhKeys.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          // 如果要处理的是日期格式，需要特殊的转换
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = new Date(formatExcelDate(item[zhKey]))
          } else {
            obj[enKey] = item[zhKey]
          }
        })
        return obj
      })
    },
    async handleSuccess({ results, header }) {
    //   console.log('读出来的excel的内容是', results, header)
      // 1. 转格式，按接口文档的要求
      //    (1) 中文的属性名 转成英文
      //   （2） 日期时间，要额外处理
      const data = this.transformData(results)
      console.log(data)
      try {
        // 2.调用接口，传入转换之后的数据
        await importEmployee(data)
        this.$message.success('ok')
        this.$router.back()
      } catch (err) {
        this.$message.error(err.message)
      }
    }
  }
}
</script>
